﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using WindowsFormsApp1.Model;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private LunarModel lunarModel; //数据结构
        private int inputYear; //输入的年
        private int inputMoth; //输入的月
        private int inputDay; //输入的日

        public Form1()
        {
            InitializeComponent();
            lunarModel = new LunarModel();
            inputYear = 0;
            inputMoth = 0;
            inputDay = 0;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            string filePath = "res/LunarDate.json";
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("The JSON file was not found.", filePath);
            }
            // 读取文件内容
            string json = File.ReadAllText(filePath);
            lunarModel = JsonConvert.DeserializeObject<LunarModel>(json);
            //Console.WriteLine(lunarModel.lunarYear);
        }

        //年份计算
        private void yearTextBox_TextChanged(object sender, EventArgs e)
        {
            DateTime nowTime = DateTime.Today; //现在的时间
            int nowYear = nowTime.Year; //获取当前年份

            var year = yearTextBox.Text.ToString(); //获取年份输入框的字符串
            if (year == null || year == "")//字符串为空时
            {
                lYearlabel.Text = null;
                return;
            }

            inputYear = int.Parse(year);
            if (inputYear > nowYear)
            {
                MessageBox.Show("不可大于" + nowYear);
                return;
            }
            try
            {
                var timeZoom = (inputYear - 1900) % 12; //1900为鼠年 子 地支
                var tgYear = inputYear % 10; //年份天干
                if (timeZoom >= 0 && tgYear >= 0)
                {
                    //string[] zoomYear = { "子宫", "丑宫", "寅宫", "卯宫", "辰宫", "巳宫", "午宫", "未宫", "申宫", "酉宫", "戌宫", "亥宫" }; //数组
                    //年份地支
                    JArray jArray = (JArray)lunarModel.lunarYear;
                    List<string> zoomYear = jArray.ToObject<List<string>>(); //数组
                    //年份天干
                    JArray tgArray = (JArray)lunarModel.luanrTg;
                    List<string> tgYearStr = tgArray.ToObject<List<string>>(); //数组

                    //zoomTextBox.Text = zoomYear[timeZoom];
                    lYearlabel.Text = tgYearStr[tgYear] + zoomYear[timeZoom];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //计算月份 （年干*2+1）= 月干 
        private void mothTextBox_TextChanged(object sender, EventArgs e)
        {
            if (inputYear == 0)
            {
                MessageBox.Show("输入年份");
                return;
            }
            //为空
            if (mothTextBox.Text.ToString() == "" || mothTextBox.Text.ToString() == null)
            {
                return;
            }
            inputMoth = int.Parse(mothTextBox.Text.ToString());
            if (inputMoth > 12)
            {
                MessageBox.Show("不可大于12");
                return;
            }
            //输入的年份最后一位
            //var timeZoom = (inputYear - 1900) % 12; //1900为鼠年 子 地支
            var tgYear = inputYear % 10; //年份天干
            //月干
            var m = (tgYear + 2) * 2 + inputMoth;
            //Console.WriteLine(num + "\n" + m);
            int mm = (m - 1) % 10;
            //Console.WriteLine(mm);
            //月份天干
            JArray tgArray = (JArray)lunarModel.dayTg;
            List<string> tgMothStr = tgArray.ToObject<List<string>>(); //数组
            //Console.WriteLine(tgMothStr[mm].ToString());
            var taText = tgMothStr[mm].ToString();
            //地支
            int dzNum = inputMoth + 1;
            if (dzNum >= 12)
            {
                dzNum = dzNum % 12;
            }
            Console.WriteLine(dzNum);
            JArray dzArray = (JArray)lunarModel.lunarYear;
            List<string> dzMothStr = dzArray.ToObject<List<string>>(); //数组
            var dzText = dzMothStr[dzNum].ToString();
            //Console.WriteLine(dzMothStr.Count);
            lMothLabel.Text = taText + dzText;

        }
        /**
         * 日计算 
         * 【（阳历公元年数-1）×5+（阳历公元年数-1）/4+（年初距离预测日期总日数）】÷60 
         * 日天干序数=以上公式所得余数（余数小于10时加10）÷10所得余数
         * 日地支序数=以上公式所得余数（余数小于12时加12）÷12所得余数
         */

        private void dayTextBox_TextChanged(object sender, EventArgs e)
        {
            //Console.WriteLine(dayTextBox.Text.ToString());
            if (dayTextBox.Text.ToString() == "" || dayTextBox.Text.ToString() == null)
            {
                return;
            }
            try
            {
                inputDay = int.Parse(dayTextBox.Text.ToString()); //输入的日
                if (inputDay > 31)
                {
                    dayTextBox.Text = "1";
                    MessageBox.Show("不可输入大于31的数");
                    return;
                }
                if (inputYear > 0 && inputMoth > 0 && inputDay > 0)
                {
                    //DateTime nowTime = DateTime.Today; //现在的时间
                    //                                   //Console.WriteLine($"现在的时间: {nowTime}");
                    //int nowYear = nowTime.Year; //获取当前年份
                    //DateTime nowYearFirstDay = new DateTime(nowYear, 1, 1); //年初的时间 即 当前年份/1月/1日 
                    //Console.WriteLine($"获取当前年份: {nowYearFirstDay}");
                    //TimeSpan daysSinceNewYear = nowTime - nowYearFirstDay; //从年初到的时间间隔

                    DateTime inputTime = new DateTime(inputYear, inputMoth, inputDay); //输入的时间 重组
                    DateTime nowYearFirstDay = new DateTime(inputYear, 1, 1); //输入的时间 重组
                    TimeSpan daysSinceNewYear = inputTime - nowYearFirstDay; //从年初到的时间间隔
                    int days = daysSinceNewYear.Days; // 转换为天数
                                                      //Console.WriteLine($"从年初到今天的天数为: {days}");

                    int dayDiff = (((inputYear - 1) * 5) + ((inputYear - 1) / 4) + days) % 60;
                    Console.WriteLine($"从年初到今天的天数为: {dayDiff}");


                    var dayTg = (dayDiff + 10) % 10; //日天干序数
                    var dayDz = (dayDiff + 12) % 12; //日地支序数为

                    Console.WriteLine($"从年初到今天的天数为: {dayTg} \n" + dayDz);

                    //日 地支
                    JArray jArray = (JArray)lunarModel.lunarYear;
                    List<string> zoomDay = jArray.ToObject<List<string>>(); //数组
                    //日 天干
                    JArray tgArray = (JArray)lunarModel.dayTg;
                    List<string> tgDayStr = tgArray.ToObject<List<string>>(); //数组
                    //Console.WriteLine(jArray + "\n" + tgArray);
                    lDayLabel.Text = tgDayStr[dayTg].ToString() + zoomDay[dayDz].ToString();
                    return;
                }
                else
                {
                    MessageBox.Show("请输入年和月");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        //时辰选择
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var sf = hourComboBox.SelectedIndex.ToString();
            lHourLabel.Text = hourComboBox.Text.ToString();
            Console.WriteLine(sf);
        }

        //排盘按钮
        private void paipanButton_Click(object sender, EventArgs e)
        {
            var mgIndex = int.Parse(mgComboBox.SelectedIndex.ToString());

            string text = "姓名：" + nameTextBox.Text.ToString()
                + "\n"
             + "命宫：" + mgComboBox.Text // 这里可以是变量字符串
            + "\n"
            + "年：" + lYearlabel.Text.ToString()
             + "\n"
            + "月：" + lMothLabel.Text.ToString()
             + "\n"
            + "日：" + lDayLabel.Text.ToString()
             + "\n"
            + "时：" + hourComboBox.Text.ToString();

            DateTime currentTime = DateTime.Now;
            DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan timeSpan = currentTime.Subtract(unixEpoch);
            long timestamp = (long)timeSpan.TotalSeconds;

            string imagePath = nameTextBox.Text.ToString() + "_" + timestamp + ".png"; // 图片保存路径
            CreateImage(text, imagePath);
        }

        //生成图片
        public static void CreateImage(string text, string path)
        {
            // 创建一个位图实例，可以根据需要调整大小
            using (Bitmap image = new Bitmap(600, 300))
            {
                using (Graphics graphic = Graphics.FromImage(image))
                {
                    // 设置背景颜色和文字颜色
                    graphic.Clear(Color.White);
                    Color textColor = Color.Black;

                    // 设置文字格式（例如：字体、大小、样式等）
                    Font font = new Font("Arial", 20, FontStyle.Bold);

                    // 测量文字大小
                    SizeF textSize = graphic.MeasureString(text, font);

                    // 在图片上绘制文字
                    PointF point = new PointF(
                        (image.Width - textSize.Width) / 2,
                        (image.Height - textSize.Height) / 2);
                    graphic.DrawString(text, font, new SolidBrush(textColor), point);

                    // 保存图片到指定路径
                    image.Save(path, ImageFormat.Png);
                }
            }
        }
    }
}
